package zk;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * @Title: ZKConnectDemo.java
 * @Description: zookeeper 恢复之前的会话连接demo演示
 */
public class ZKConnectSessionWatcher implements Watcher {
	
	final static Logger log = LoggerFactory.getLogger(ZKConnectSessionWatcher.class);

	public static final String zkServerPath = "127.0.0.1:2181";
	public static final Integer timeout = 5000;
	
	public static void main(String[] args) throws Exception {
		
		ZooKeeper zk = new ZooKeeper(zkServerPath, timeout, new ZKConnectSessionWatcher());
		
		long sessionId = zk.getSessionId();
		String ssid = "0x" + Long.toHexString(sessionId);
		System.out.println(ssid);
		byte[] sessionPassword = zk.getSessionPasswd();
		System.out.println(new String(sessionPassword));
		log.warn("客户端开始连接zookeeper服务器...");
		log.warn("连接状态：{}", zk.getState());
		new Thread().sleep(1000);
		log.warn("连接状态：{}", zk.getState());
		
		new Thread().sleep(200);
		
		// 开始会话重连
		log.warn("开始会话重连...");
		
		ZooKeeper zkSession = new ZooKeeper(zkServerPath, 
											timeout, 
											new ZKConnectSessionWatcher(), 
											sessionId, 
											sessionPassword);
		log.warn("重新连接状态zkSession：{}", zkSession.getState());
		new Thread().sleep(1000);
		log.warn("重新连接状态zkSession：{}", zkSession.getState());

//		String res = zk.create("/linshi","java".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);

//		System.out.println(res);
		zk.create("/async1", "aaa".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
				CreateMode.EPHEMERAL, new AsyncCallback.StringCallback() {
					@Override
					public void processResult(int rc, String path, Object ctx, String name) {
						System.out.println("创建节点："+path);
						System.out.println("name:"+name);
						System.out.println((String)ctx);
					}
				},"create:sucess");
		new Thread().sleep(3000);
		Stat stat = new Stat();
		//zk.setData("/java","lala".getBytes(),0);
		byte[] bytes = zk.getData("/java",false,stat);
		System.out.println(new String(bytes));
		System.out.println("0x"+Long.toHexString(stat.getCzxid()));
		zk.delete("/java",1);
	}
	
	@Override
	public void process(WatchedEvent event) {
		log.warn("接受到watch通知：{}", event);
	}
}

